﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using YAPL.Language.Ast;
using YAPL.Util;

namespace YAPL.Language.SourceParser.XML.NodeParsers {
	public class XmlFunctionCallParser : XmlExpressionParser {
		public XmlFunctionCallParser(XmlInputParser inputParser) : base(inputParser) {}
		public override Expression ParseNode(XElement node) {
			var methodAttribute = node.Attribute(XmlNames.FunctionCallNameAttribute);

			Require.NotNull(methodAttribute);
			Require.NotEmpty(methodAttribute.Value);

			var argumentsNode = node.Element(XmlNames.ArgumentsExpression);
			var callingObjectNode = node.Element(XmlNames.CallingObjectExpression);

			var arguments = new List<Expression>();

			//TODO select proper value for empty calling object
			Expression callingObject = null;

			if (argumentsNode != null) {
				var argumentNodes = argumentsNode.Elements();
				argumentNodes.Each(element => arguments.Add(Parser.ParseNode(element)));
			}

			if (callingObjectNode != null) {
				callingObject = Parser.ParseNode(callingObjectNode.Elements().First());
			}

			return Expressions.FunctionCall(methodAttribute.Value, arguments, callingObject);
		}
	}
}
